package org.huzhp.security.wx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @Description 微信登录集成
 * @Author huzp
 * @Data 2019/3/28
 * @Version 1.0
 */
@Component
@EnableConfigurationProperties(WxAuthProperties.class)
public class WxAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private WxAuthenticationSuccessHandler oauth2AuthenticationSuccessHandler;
    @Autowired
    private WxAuthenticationFailureHandler oauth2AuthenticationFailureHandler;

//    @Autowired
//    private SessionRegistry sessionRegistry;

    public static final String urlPath = "/wxLogin";

    @Autowired
    private WxAuthProperties wxAuthProperties;


    @Override
    public void configure(HttpSecurity http) {
        WxAuthenticationFilter oauth2AuthenticationFilter = new WxAuthenticationFilter();
        oauth2AuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        oauth2AuthenticationFilter.setAuthenticationSuccessHandler(oauth2AuthenticationSuccessHandler);
        oauth2AuthenticationFilter.setAuthenticationFailureHandler(oauth2AuthenticationFailureHandler);

//        RegisterSessionAuthenticationStrategy authenticationStrategy = new RegisterSessionAuthenticationStrategy(sessionRegistry);
//        oauth2AuthenticationFilter.setSessionAuthenticationStrategy(authenticationStrategy);

        WxAuthenticationProvider wxAuthenticationProvider = new WxAuthenticationProvider();
        wxAuthenticationProvider.setUserDetailsService(getWxUserDetailService());
        http.requestMatchers().antMatchers(urlPath);
        http.authenticationProvider(wxAuthenticationProvider)
                .addFilterBefore(oauth2AuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public WxUserDetailService getWxUserDetailService() {
        WxUserDetailService wxUserDetailService = new WxUserDetailService(wxAuthProperties);
        return wxUserDetailService;
    }

}
